package com.example.springboot.utils;

import java.util.Date;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.springboot.entity.User;
import com.example.springboot.service.UserService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;


@Component
public class TokenUtils {

    private static UserService staticUserService;

    @Resource
    UserService userService;

    @PostConstruct
    public void setUserService(){
        staticUserService=userService;
    }

    // 生成token
    public static String createToken(String userCount,String sign){
        return JWT.create().withAudience(userCount)//将user count保存到token里面,作为载荷
            .withExpiresAt(DateUtil.offsetHour(new Date(),2))//两小时后token过期
            .sign(Algorithm.HMAC256(sign));//以pwd作为token的密钥
    }

    // 获取当前登录用户的信息
    public static User getCurrentUser(){
        try{
            HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            String token=request.getHeader("token");
            if(StrUtil.isNotBlank(token)){
                String userCount=JWT.decode(token).getAudience().get(0);
                return staticUserService.selectByCount(userCount);
            }
        }catch(Exception e){
            return null;
        }
        return null;
    }
}
